#!/usr/bin/env Rscript
if (!require("librarian", quietly = TRUE))
  install.packages("librarian")
library(librarian)
shelf(rvest, readr, tibble, dplyr, stringr, purrr, lubridate)

message.mail <- function(subj, msg){
  require(mailR)
  
  send.mail(from = account$sender, to = account$recipients,
            subject = subj,
            body = msg,
            smtp = list(host.name = "smtp.qq.com", port = 587, user.name = account$sender,
                        passwd = account$token, ssl = TRUE),
            authenticate = TRUE, debug = T, send = TRUE)
  
  message('Email successfully sent.')
}

now() |> print()

account <- read_csv('~/learn/myhome_monitor/account.csv', show_col_types = FALSE)

water_threshold <- 20
electr_threshold <- 20

# login -----------------
sess <- session('http://myhome.tsinghua.edu.cn/web_netweb_user/noLogin.aspx')

login.form <- sess |> html_form() |>
  pluck(1)

login.form <- login.form |>
  html_form_set('net_Default_LoginCtrl1$txtUserName' = account$user,
                'net_Default_LoginCtrl1$txtPassword' = account$passwd)

resp <- session_submit(sess, login.form)

# scrape balances ---------
water_balance <- resp |>
  session_jump_to('http://myhome.tsinghua.edu.cn/web_Netweb_List/Netweb_Home_water_Detail.aspx') |>
  read_html() |>
  html_element('#Netweb_Home_water_DetailCtrl1_lblele') |>
  html_text2() |>
  str_remove('元') |>
  as.numeric()

electr_balance <- resp |>
  session_jump_to('http://myhome.tsinghua.edu.cn/web_Netweb_List/Netweb_Home_electricity_Detail.aspx') |>
  read_html() |>
  html_element('#Netweb_Home_electricity_DetailCtrl1_lblele') |>
  html_text2() |>
  as.numeric()

# record to disk -----------
if (water_balance & electr_balance) {
  stat_dorm <- tibble(time = today(),
                      water_rmb = water_balance,
                      electr_kwh = electr_balance)
  
  message('Query is successful. Writing to disk.')
  
  read_csv('~/learn/myhome_monitor/stat.dorm.csv', show_col_types = FALSE) |>
    bind_rows(stat_dorm) |>
    write_csv('~/learn/myhome_monitor/stat.dorm.csv')
  
  # Send the email if balance is low ------------
  
  if (water_balance < water_threshold | electr_balance < electr_threshold) {
    message('Balance is low. Sending alert email.')
    
    message.mail(subj = "[Warning] Utility balance alert",
                 msg = str_glue("Warning. Utility balance is low.
                          Record Date = {today()}
                          Water balance (RMB) = {water_balance}
                          Electricity balance (kWh) = {electr_balance}
                          Please recharge."))
  }
} else {
  message('Query failed. Sending alert email.')
  
  message.mail(subj = "[Warning] Monitor query failed",
               msg = str_glue("Warning. Monitor query failed.
                          Please check the log."))
}


